const { request, clearAuth } = require('../../utils/request');
const pageBehavior = require('../../utils/pageBehavior');

Page({
  behaviors: [pageBehavior],

  data: {
    loading: false,
    errorMessage: '',
    userProfile: null
  },

  onShow() {
    this.setData({ errorMessage: '' });
  },

  async handleWeappLogin() {
    if (this.data.loading) return;
    this.setData({ loading: true, errorMessage: '' });
    wx.showLoading({ title: '正在登录', mask: true });

    try {
      const codeResult = await this.acquireLoginCode();
      const profile = await this.acquireUserProfile();
      const profileInfo = {
        nickName: profile.nickName || '',
        avatarUrl: profile.avatarUrl || '',
        unionId: profile.unionId || ''
      };
      this.setData({ userProfile: profileInfo });

      // 示例：后端将使用 appId + appSecret + code 调用微信 jscode2session 接口换取 openid/unionid
      // POST /api/miniapp/user/login 负责编排上述流程并写入数据库
      const response = await request({
        url: '/api/miniapp/user/login',
        method: 'POST',
        data: {
          code: codeResult.code,
          nickName: profileInfo.nickName,
          avatarUrl: profileInfo.avatarUrl,
          unionId: profileInfo.unionId
        },
        suppressAuth: true,
        showErrorToast: false
      });

      const token = response?.data?.token;
      const student = response?.data?.student || {};
      if (!token || !student.id) {
        throw new Error(response?.message || '登录失败');
      }

      const auth = require('../../utils/auth');
      auth.setAuth(token, student);

      // 本地缓存微信标识，unionId 可能为空
      wx.setStorageSync('student.openid', student.id);
      if (student.unionId) {
        wx.setStorageSync('student.unionid', student.unionId);
      }

      // 将昵称与头像与 openid 绑定（待后端接口完善时直接提交）
      // 示例：POST /api/miniapp/user/profile { openid, nickName, avatarUrl }
      wx.setStorageSync('profile.snapshot', {
        ...student,
        nickName: student.nick || profileInfo.nickName,
        avatarUrl: student.avatar || profileInfo.avatarUrl
      });

      const app = getApp();
      if (app && typeof app.setAuthState === 'function') {
        app.setAuthState(true, wx.getStorageSync('profile.snapshot'));
      }

      wx.showToast({ title: '登录成功', icon: 'success' });
      setTimeout(() => {
        wx.switchTab({ url: '/pages/profile/profile' });
      }, 400);
    } catch (error) {
      const message = error?.message || '登录失败';
      this.handleFailure(message);
    } finally {
      wx.hideLoading();
      this.setData({ loading: false });
    }
  },

  acquireLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        timeout: 10000,
        success: (res) => {
          if (res.code) {
            resolve(res);
          } else {
            reject(new Error('未获取到微信登录凭证'));
          }
        },
        fail: (err) => reject(err || new Error('微信登录失败'))
      });
    });
  },

  acquireUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => resolve(res?.userInfo || {}),
        fail: (err) => reject(err || new Error('未授权用户信息'))
      });
    });
  },

  handleFailure(message) {
    clearAuth();
    this.setData({ errorMessage: message });
    wx.showToast({ title: message, icon: 'none' });
    setTimeout(() => {
      wx.switchTab({ url: '/pages/profile/profile' });
    }, 400);
  }
});
